import axios from 'axios'
import { Loading } from 'element-ui'
import dataCache from '@/utils/dataCache.js'

const DEAFULT_LOADING = true
export default class Request {
  instance
  loading
  showLoading

  constructor (config) {
    this.instance = new axios.create(config)
    this.showLoading = config.showLoading ?? DEAFULT_LOADING
    // 请求拦截器
    this.instance.interceptors.request.use(config => {
      if (this.showLoading) {
        this.loading = Loading.service({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // 携带token的拦截
        const token = dataCache.getCache('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        // console.log('拦截请求信息成功')
        return config
      }
    },
    (error) => {
      return error
    })
    // 响应拦截器
    this.instance.interceptors.response.use(res => {
      this.loading.close()
      return res.data
    },
    (error) => {
      return error
    })
  }

  request (config) {
    return new Promise((resolve, reject) => {
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }

      this.instance
        .request(config)
        .then((res) => {
          // 将showLoading设置成默认值，这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          // 返回数据
          resolve(res)
        })
        .catch((error) => {
          // 将showLoading设置成默认值，这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          reject(error)
        })
    })
  }

  get (config) {
    return this.request({ ...config, method: 'GET' })
  }

  post (config) {
    return this.request({ ...config, method: 'POST' })
  }

  delete (config) {
    return this.request({ ...config, method: 'DELETE' })
  }

  put (config) {
    return this.request({ ...config, method: 'PUT' })
  }
}
